package myapp.helper;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import myapp.EnumAndConstans.Constants;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class Utils {
	
	public static String getText(int id, View v){
		EditText widget = (EditText) v.findViewById(id);
		return widget.getText().toString();
	}
	
	public static String makeDataRequest(String receiverEmail, String requesterEmail){
		String data = Constants.REQUESTER_EMAIL_KEYWORD + 
				requesterEmail + 
				" " + 
				Constants.RECEIVER_EMAIL_KEYWORD + 
				receiverEmail;		
		
		return data;
	}
	
	private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfbyte = (b >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
                halfbyte = b & 0x0F;
            } while (two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }
    
    /**
     * Covert a string to  multiline strings
     * @param input: string
     * @param max_length: max length each line
     * @return
     */
    public static String StringToMultiLineString(String input, int max_length)
    {Log.i("StringToMultiLineString", input);
    	String result = "";
    	if (input.length() <= max_length)
    		return input;
    	
    	String[] separated = input.split(" ");
    	String next = "";
    	String previous = "";
    	for (int i = 0; i < separated.length; i++)
    	{
    		next += separated[i] + " ";
    		if (i == separated.length - 1)
    		{
    			result += next;
    			break;
    		}
    		if (next.length() > max_length)
    		{
    			result += previous + "\n";
    			next = separated[i] + " ";
    		}
    		else
    			previous = next;
    	}
    	Log.i("StringToMultiLineString", result);
    	return result;
    }
    
    public static void showAlertDialog(Context context, int titleId, int msgId, int iconId){
    	Log.i("Utils", "[showAlertDialog] showAlertDlg");
    	AlertDialog.Builder alert = new AlertDialog.Builder(context);
		alert.setTitle(titleId);
		alert.setMessage(msgId);
		if (iconId != Constants.NOT_AVAILABLE){
			alert.setIcon(iconId);
		}
		alert.show();
    }
}
